Ext.define("Admin.view.emergencyDispatch.ContaminantsTrackController", {
    extend: "Ext.app.ViewController",
    alias: "controller.contaminantsTrack",
    config: {
        map: null,
        dojo: null,
        markSy: null,
        graphic: null,
    },

    //详情弹出框
    onHisDataReadClick: function() {
        var _that = this;
        var win = _that.lookupReference("historyWindow");
        var evenCd = _that.lookupReference("evenCd").getValue(); //事件ID

        var downsec = _that.lookupReference("downsec"); //下监测断面
        var dowvalue = downsec.getValue().trim();

        if (dowvalue == 'self') {
            downsec.rawValue = '自定义';
        } else {

        }
        var begt = _that.lookupReference('begt').getValue();
        var edt = _that.lookupReference('edt').getValue();

        if (!begt || !edt) {
            Ext.Msg.alert("系统提示", "起始/结束计算时间必选选择!");
            return;
        }
        if (!win) {
            win = Ext.create("Ext.window.Window", {
                title: downsec.rawValue + "断面设置",
                width: 500,
                padding: false,
                resizable: false,
                reference: "historyWindow",
                autoScroll: true,
                items: [{
                    // Let's put an empty grid in just to illustrate fit layout
                    xtype: "hisDataRead",
                    layout: {

                        type: "vbox",
                        pack: "start",
                        align: "stretch"
                    }
                }, {
                    type: 'panel',
                    border: true,
                    height: 45,
                    padding: false,

                    tbar: ['->', {
                            xtype: "button",
                            width: 80,
                            text: "保存",
                            reference: 'hisDataReadoksave',
                            handler: function() {
                                var form = _that.lookupReference("hisDataReadform").getForm();
                                var rcd = _that.lookupReference('rcd').getValue();
                                var values = form.getValues();
                                values.rcd = rcd;
                                values.flag = 1;
                                values.river = config.RIVER;
                                if (form.isValid()) {
                                    Ext.Ajax.request({
                                        url: config.URL + "emergency/ddsmconsec/save",
                                        method: "post",
                                        success: function(response, opts) {
                                            Ext.MessageBox.hide();
                                            var result = Ext.JSON.decode(response.responseText);
                                            Ext.MessageBox.hide();
                                            if (result.code === 1) {
                                                Ext.Msg.alert("系统提示", "保存成功！");
                                                win.hide();
                                            } else {
                                                Ext.Msg.alert("系统提示", result.msg);
                                            }
                                        },
                                        failure: function() {
                                            Ext.Msg.alert("系统提示", "系统出错！");
                                        },
                                        params: values
                                    });
                                }
                            }
                        },
                        {
                            xtype: "button",
                            width: 80,
                            text: "取消",
                            handler: function() {
                                win.hide();
                            }
                        }
                    ]
                }]
            });
            this.getView().add(win);
        }

        var secname = _that.lookupReference("secname");
        var secmils = _that.lookupReference("secmils");
        var lgtd = _that.lookupReference('lgtd');
        var lttd = _that.lookupReference('lttd');
        var lgtdlttd = _that.lookupReference('lgtdlttd');
        var hisDataReadoksave = _that.lookupReference("hisDataReadoksave");

        var surfaceSettingGrid = _that.lookupReference("surfaceSettingGrid"); //断面设置的表格

        var form = _that.lookupReference("hisDataReadform").getForm();
        form.reset();
        if (dowvalue == 'self') {
            secname.setDisabled(false);
            secmils.setDisabled(false);
            lgtd.setDisabled(false);
            lgtdlttd.setDisabled(false);
            hisDataReadoksave.setDisabled(false);
            var store = Ext.create("Ext.data.Store", {
                autoLoad: true,
                data: []
            });
            surfaceSettingGrid.setStore(store);
        } else {
            var lenup = 0;

            var secid = downsec.getValue();
            // surfaceSettingGrid.setHidden(false);
            for (var i = 0; i < mconsecList.length; i++) {
                if (mconsecList[i].secid == secid) {
                    lenup = mconsecList[i].lenup;
                }
            }
            secname.setValue(downsec.rawValue);
            secmils.setValue(lenup);
            secname.setDisabled(true);
            secmils.setDisabled(true);
            lgtdlttd.setDisabled(true);
            hisDataReadoksave.setDisabled(true);
            var store = Ext.create("Ext.data.Store", {
                autoLoad: true,
                proxy: {
                    type: "ajax",
                    url: config.URL + "emergency/DdsEdWqData/listdefault",
                    extraParams: {
                        river: config.RIVER,
                        evenCd: evenCd,
                        begt: Ext.Date.format(begt, "Y-m-d H:i:s"),
                        edt: Ext.Date.format(edt, "Y-m-d H:i:s"),
                        downsec: secid
                    },
                    reader: {
                        type: "json",
                        rootProperty: "list"
                    }
                }
            });
            surfaceSettingGrid.setStore(store);
        }
        win.show();
    },

    //断面设置單元格修改
    surfaceSettingGridEdit: function(editor, context, eOpts) {
        var value = context.record.getData();
        value.c = context.value;
        var state; //返回的狀態嘛
        Ext.Ajax.request({
            url: config.URL + "emergency/DdsEdWqData/update",
            method: "post",
            success: function(response, opts) {
                Ext.MessageBox.hide();
                var result = Ext.JSON.decode(response.responseText);
                if (result.code === 1) {
                    state = true;
                    Ext.toast({
                        html: result.msg,
                        width: 200,
                        align: 't'
                    });

                } else {
                    state = false;
                    Ext.toast({
                        html: result.msg,
                        width: 200,
                        align: 't'
                    });
                }
            },
            failure: function() {
                state = false;
                Ext.Msg.alert("系统提示", "系统出错！");
            },
            params: value
        });
        return state;
    },

    downloadFile: function() {
        window.open(config.URL + "emergency/DdsEdWqData/downtempletfile?river=" + config.RIVER);
    },

    //溯源模拟
    imitateTrack: function() {
        var _that = this;
        var tscale = _that.lookupReference("tscale").getValue(); //时间尺度
        var evenCd = _that.lookupReference("evenCd").getValue(); //事件ID
        var upsec = _that.lookupReference("upsec").getValue(); //上监测断面
        var downsec = _that.lookupReference("downsec").getValue(); //下监测断面
        var avgflow = _that.lookupReference("avgflow").getValue(); //平均流速
        var begt = _that.lookupReference("begt").getValue(); //开始时间
        var edt = _that.lookupReference("edt").getValue(); //結束时间
        var rcd = _that.lookupReference("rcd").getValue(); //結束时间
        console.log(_that.lookupReference("rcd"));
        var daType = _that.lookupReference("daType").getValue(); //污染物类型
        var method = _that.lookupReference("method").getValue(); //溯源方式

        var lenUp; //距离上监测的距离
        mconsecList.forEach(function(item) {
            if (item.secid == downsec) {
                lenUp = item.lenup;
            }
        });
        var params = {
            tscale: tscale,
            evenCd: evenCd,
            downsec: downsec,
            upsec: upsec,
            rcd: rcd,
            daType: daType,
            method: method,
            q: avgflow,
            lenUp: lenUp,
            begt: Ext.Date.format(begt, "Y-m-d H:i:s"),
            edt: Ext.Date.format(edt, 'Y-m-d H:i:s'),
            river: config.RIVER
        };
        for (var key in params) {
            if (params[key] == '') {

                Ext.Msg.alert('提示', (_that.lookupReference(key) ? _that.lookupReference(key).getFieldLabel() : (key === "lenUp" ? "下检测断面" : key)) + '不得为空!');
                return;
            }
        }
        Ext.Ajax.request({
            url: config.URL + "emergency/ddsEdSource/getresult",
            method: "post",
            timeout: 300000,
            success: function(response, opts) {
                var result = Ext.JSON.decode(response.responseText).result;
                _that.lookupReference("tmResult").setValue(new Date(result.tm));
                _that.lookupReference("surfaceDistanceResult").setValue(result.lenUp);
                _that.lookupReference("continueTm").setValue(result.dur);
                _that.lookupReference("pollutionLoad").setValue(result.da);
            },
            failure: function() {
                Ext.Msg.alert("系统提示", "系统出错！");
            },
            params: params
        });

    },

    setCondition: function(value) {
        Ext.Ajax.request({
            url: config.URL + "emergency/ddsEdSource/listinit",
            method: "get",
            success: function(response, opts) {
                var result = Ext.JSON.decode(response.responseText);
                if (result.listevent) {
                    var listevent = result.listevent;
                    listevent.forEach(function(item) {
                        if (item.evenCd === value) {}
                    });
                } else {
                    Ext.Msg.alert("系统提示", "获取数据失败");
                }
            },
            failure: function() {
                Ext.Msg.alert("系统提示", "系统出错！");
            },
            params: {
                river: config.RIVER
            }
        });
    },

    eventListRender: function(combo) {
        var _that = this;
        var evenCdObj = _that.lookupReference('evenCd');
        Ext.Ajax.request({
            url: config.URL + "emergency/ddsEdSource/listinit",
            // url: config.URL + "emergency/ddsEdEvent/list",
            method: "post",
            success: function(response, opts) {
                Ext.MessageBox.hide();
                var result = Ext.JSON.decode(response.responseText);
                console.log(result);
                var listevent = result.listevent;
                evenCdObj.setStore({
                    fields: ["evenNm", "evenCd", "rcd"],
                    data: listevent
                });
                _that.getViewModel().setData({
                    resourceLists: result.resource
                });
                var evenCdValue = config.contaminantsTrackEvenCd ? config.contaminantsTrackEvenCd : listevent[0].evenCd;
                _that.lookupReference('evenCd').setValue(evenCdValue);
            },
            failure: function() {
                Ext.Msg.alert("系统提示", "系统出错!");
            },
            params: {
                river: config.RIVER
            }
        });
    },

    changeEvent: function(combo, newValue, oldValue) {
        var _that = this;
        var resourceLists = _that.getViewModel().getData().resourceLists;
        console.log(resourceLists);
        var downsec = _that.lookupReference("downsec"); //下监测断面
        if (resourceLists[newValue] && newValue !== oldValue) {
            resourceLists[newValue].begt = resourceLists[newValue].begt ? resourceLists[newValue].begt : '';
            resourceLists[newValue].edt = resourceLists[newValue].edt ? resourceLists[newValue].edt : '';
            resourceLists[newValue].tm = resourceLists[newValue].tm ? resourceLists[newValue].tm : '';
        }

        var alldata = combo.getStore().getData().items;
        var rcd = '';
        for (var i = 0; i < alldata.length; i++) {
            if (newValue == alldata[i].data.evenCd) {
                rcd = alldata[i].data.rcd;
                var locname = getRnm(rcd) ? getRnm(rcd) : "";
                _that.lookupReference('locname').setValue(locname);
            }
        }
        _that.lookupReference('rcd').setValue(rcd);
        _that.getViewModel().setData({
            resource: resourceLists[newValue]
        });
        downsec.setValue('self');
        _that.riverChange(rcd);


    },

    //追踪溯源方式切换
    methodChange: function(combo, newValue, oldValue) {
        var _that = this;
        var upsec = _that.lookupReference('upsec');
        var downsec = _that.lookupReference('downsec');
        var begt = _that.lookupReference('begt');
        var edt = _that.lookupReference('edt');
        var tscale = _that.lookupReference('tscale');
        var avgflow = _that.lookupReference('avgflow');
        var downsecbutton = _that.lookupReference('downsecbutton');
        if (newValue == 2) {
            upsec.setDisabled(true);
            downsec.setDisabled(true);
            begt.setDisabled(true);
            edt.setDisabled(true);
            tscale.setDisabled(true);
            avgflow.setDisabled(true);
            downsecbutton.setDisabled(true);

        } else {
            upsec.setDisabled(false);
            downsec.setDisabled(false);
            begt.setDisabled(false);
            edt.setDisabled(false);
            tscale.setDisabled(false);
            avgflow.setDisabled(false);
            downsecbutton.setDisabled(false);

        }
    },

    //当河道列表发生变化时
    riverChange: function(newValue) {
        var _that = this;
        var upsec = this.lookupReference("upsec"); //上断面
        var downsec = this.lookupReference("downsec"); //下断面
        var getData = function(obj, id, type) {
            var _result = [];
            obj.forEach(function(item) {
                if (item.rcd == id && item.secflag == type && item.river == config.RIVER) {
                    _result.push({
                        label: item.secnm,
                        value: item.secid
                    });
                }
            });
            return _result;
        };
        //获取上断面的store
        var upStoreData = getData(mconsecList, newValue, "up");
        var upStore = Ext.create('Ext.data.Store', {
            fields: ["label", "value"],
            data: upStoreData
        });
        _that.getViewModel().setData({
            upsecStore: upStore
        });
        if (upStoreData.length > 0) {
            upsec.setValue(upStoreData[0].value);
        } else {
            upsec.setValue('');
        }
        //下河道监测断面的store
        var downStoreData = getData(mconsecList, newValue, "down").concat([{
            label: "自定义",
            value: "self"
        }]);
        var downStore = Ext.create("Ext.data.Store", {
            fields: ["label", "value"],
            data: downStoreData
        });
        _that.getViewModel().setData({
            downsecStore: downStore
        });
        downsec.setValue('self');
    },

    //保存数据
    saveData: function() {
        var _that = this;
        var refs = _that.getReferences();
        var evenCd = refs.evenCd.getValue(); //选择应急事件
        var begt = refs.begt.getValue(); //起始计算时间
        var edt = refs.edt.getValue(); //结束计算时间
        if (begt > edt) {
            Ext.Msg.alert('提示', '起始计算时间需要小于结束计算时间'); //这种方式非常常见的
            return;
        }
        var tscale = refs.tscale.getValue(); //时间尺度
        var rcd = refs.rcd.getValue(); //河段列表
        var loc = refs.loc.getValue(); //河段列表
        var upsec = refs.upsec.getValue(); //溯源上监测断面
        var downsec = refs.downsec.getValue(); //溯源下监测断面
        var tm = refs.tmResult.getValue(); //发生时间
        var lenUp = refs.surfaceDistanceResult.getValue();
        var dur = refs.continueTm.getValue(); //持續時間
        var da = refs.pollutionLoad.getValue(); //污染量
        var avgflow = _that.lookupReference("avgflow").getValue(); //平均流速
        var lgtd = _that.lookupReference("lgtd").getValue(); //經度
        var lttd = _that.lookupReference("lttd").getValue(); //緯度
        var daType = _that.lookupReference("daType").getValue(); //污染物类型
        var method = _that.lookupReference("method").getValue(); //溯源方式
        var data = {
            evenCd: evenCd,
            begt: Ext.Date.format(begt, "Y-m-d"),
            edt: Ext.Date.format(edt, "Y-m-d"),
            tscale: tscale,
            rcd: rcd,
            loc: loc,
            upsec: upsec,
            daType: daType,
            method: method,
            downsec: downsec,
            tm: Ext.Date.format(tm, "Y-m-d"),
            lenUp: lenUp,
            da: da,
            dur: dur,
            q: avgflow,
            lgtd: lgtd,
            lttd: lttd,
            river: config.RIVER
        };
        Ext.Ajax.request({
            url: config.URL + "emergency/ddsEdSource/save",
            method: "post",
            success: function(response, opts) {
                Ext.MessageBox.hide();
                var result = Ext.JSON.decode(response.responseText);
                if (result.code === 1) {
                    Ext.Msg.alert("系统提示", "保存成功");
                } else {
                    Ext.Msg.alert("系统提示", result.msg);
                }
            },
            failure: function() {
                Ext.Msg.alert("系统提示", "系统出错！");
            },
            params: data
        });
    },
    //定位点
    // locationMap: function() {
    //     var map  = this.getMap();
    //     var dojo = this.getDojo();
    //     var clickEvent = dojo.connect(map, "onClick", function(){
    //         alert('我被点击了!!!!');
    //         dojo.disconnect(clickEvent); //点击后解绑单击事件
    //     })
    // },

    onMapInit: function(b) {
        this.initMapLayer(b);
    },
    initMapLayer: function(b) {
        var _that = this;
        require([
                "esri/request",
                "esri/graphic",
                "esri/graphicsUtils",
                "esri/layers/GraphicsLayer",
                "esri/layers/FeatureLayer",
                "esri/geometry/Point",
                "esri/geometry/Polyline",
                "esri/geometry/Polygon",
                "gis/OnlineMap",
                "esri/dijit/HomeButton",
                "dojo/_base/array",
                "esri/layers/ArcGISTiledMapServiceLayer",
                "esri/geometry/Point",
                "esri/SpatialReference",
                "esri/toolbars/draw",
                "esri/Color",
                "esri/symbols/SimpleMarkerSymbol",
                "dojo/domReady!"
            ],
            function(z, u, a, y, q, r, t, w, x, v, s, ArcGISTiledMapServiceLayer, Point, SpatialReference, Draw, Color, SimpleMarkerSymbol) {
                //b: 地图实例化对象 u: graphic
                //w: Polygon
                var layer1 = new ArcGISTiledMapServiceLayer("https://map.jxwrd.gov.cn/arcgis/rest/services/EsriBaseMap/MapServer");
                layer1.id = 'layer1';
                layer1.visible = true;
                b.addLayer(layer1);
                var p = new x("google");
                b.addLayer(p.getLayer("terrain"));

                z({
                    url: config.RIVER === "02" ? "resources/data/json/fhly.json" : "resources/data/json/yhly.json",
                    handleAs: "json"
                }).
                then(function(f) {
                    var d = [];
                    s.forEach(f.features,
                        function(j) {
                            var h = new w({
                                rings: j.geometry.rings,
                                spatialReference: f.spatialReference
                            });
                            var g = new u(h);
                            g.setAttributes(j.attributes);
                            d.push(g);
                        });
                    var c = {
                        layerDefinition: {
                            geometryType: f.geometryType,
                            objectIdField: "OBJECTID",
                            fields: f.fields,
                            drawingInfo: {
                                renderer: {
                                    type: "simple",
                                    label: "",
                                    description: "",
                                    symbol: mapconfig.symbols.boundary
                                }
                            }
                        },
                        featureSet: {
                            features: d,
                            geometryType: f.geometryType
                        }
                    };
                    lyr_boundary = new q(c, {
                        id: "BDLAYER"
                    });
                    lyr_boundary.setMaxScale(200000);
                    b.addLayer(lyr_boundary, -1);
                    var e = a.graphicsExtent(d, true);
                    b.setExtent(e);
                    //实例化定位坐标点
                    var markerSymbol = new SimpleMarkerSymbol();
                    markerSymbol.setPath("M822.336 320.512C822.336 143.488 664.448 0 489.024 0 313.536 0 160 143.488 160 320.512c0 164.16 325.312 557.12 325.312 557.12s337.024-387.52 337.024-557.12z m-438.208 11.328a110.08 110.08 0 0 1 110.4-109.696c61.056 0 110.464 49.088 110.464 109.696A110.08 110.08 0 0 1 494.528 441.6a110.144 110.144 0 0 1-110.4-109.696z m216.128 555.392a28.352 28.352 0 0 1 1.472 8.768c0 30.272-49.472 54.848-110.4 54.848-60.928 0-110.4-24.576-110.4-54.848 0-3.008 0.448-5.952 1.408-8.768-66.88 12.544-111.872 36.352-111.872 63.616 0 40.448 98.88 73.152 220.8 73.152 121.984 0 220.864-32.64 220.864-73.152-0.064-27.264-45.056-51.072-111.872-63.616z");
                    markerSymbol.setColor(new Color("#FF0000"));
                    markerSymbol.setSize(26);
                    //初始化点位
                    function addMark(geometry) {
                        if (b.graphics && b.graphics != null) b.graphics.clear();
                        var mark = new u(geometry, markerSymbol);
                        b.graphics.add(mark);
                    };
                    //给坐标定位按钮添加点击事件
                    var locationBtn = _that.lookupReference('locationBtn'); //定位按钮
                    var evenCdSelect = _that.lookupReference('evenCd');
                    var eventData = _that.getViewModel().getData().resource;
                    if (eventData.lgtd && eventData.lttd) {
                        var point = new Point(eventData.lgtd, eventData.lttd, new SpatialReference({ wkid: 4990 }));
                        var graphic = new u(point, markerSymbol);

                        var testAddGraphic = function() {
                            if (b.graphics && b.graphics != null) {
                                b.graphics.add(graphic);
                            } else {
                                setTimeout(function() {
                                    testAddGraphic();
                                }, 500);
                            }
                        }
                        testAddGraphic();
                    }
                    //创建点
                    locationBtn.on('click', function() {
                        //地图获取点位设置经纬度!
                        var tb = new Draw(b);
                        tb.on("draw-end", addGraphic); //绑定绘制事件
                        b.disableMapNavigation();
                        tb.activate('point'); //激活点绘制事件
                        function addGraphic(evt) {
                            addMark(evt.geometry);
                            tb.deactivate(); //取消绘制事件
                            b.enableMapNavigation();
                            _that.lookupReference('lgtd').setValue(evt.geometry.x);
                            _that.lookupReference('lttd').setValue(evt.geometry.y);
                        }
                    });
                    evenCdSelect.on('change', function(me, newValue, oldValue) {
                        b.graphics.clear();
                        var resourceLists = _that.getViewModel().getData().resourceLists;
                        if (resourceLists[newValue] && resourceLists[newValue].lgtd && resourceLists[newValue].lttd) {
                            var point = new Point(resourceLists[newValue].lgtd, resourceLists[newValue].lttd, new SpatialReference({ wkid: 4990 }));
                            var graphic = new u(point, markerSymbol);
                            b.graphics.add(graphic);
                        } else {
                            console.log('没有点')
                        }
                    });
                });
            }
        );
    }
});